<?php

namespace common\models\db;

use Yii;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "tbl_admin_user".
 *
 * @property int $user_id
 * @property string $user_name
 * @property string $password_hash
 * @property int $role_id
 * @property string|null $create_time
 * @property string|null $update_time
 */
class AdminUser extends BaseModel implements IdentityInterface
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'tbl_admin_user';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['user_name'], 'required', 'message' => '{attribute}不能为空'],
            [['role_id'], 'integer'],
            [['create_time', 'update_time', 'operation_setting'], 'safe'],
            [['user_name'], 'string', 'max' => 64],
            [['mobile'], 'string', 'max' => 32],
            [['password_hash'], 'string', 'max' => 128],
            [['open_id'], 'string', 'max' => 128],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'user_id' => 'User ID',
            'user_name' => '用户名',
            'password_hash' => 'Password Hash',
            'role_id' => 'Role ID',
            'mobile' => '手机号',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
        ];
    }

    public static function findIdentity($id)
    {
        return AdminUser::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return null;
    }

    public function getId()
    {
        return $this->user_id;
    }

    public function getAuthKey()
    {
        return "";
    }

    public function validateAuthKey($authKey)
    {
        return true;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     * @param $password
     * @throws \yii\base\Exception
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * @param $username
     * @return AdminUser|null
     */
    public static function findByUsername($username)
    {
        return AdminUser::findOne(['user_name' => $username]);
    }
}
